package ReflectionTest;

import java.lang.reflect.*;

// 步骤 1: 创建接口和实现类
interface ClothFactory {
    Integer produceCloth();
}

class NikeClothFactory implements ClothFactory {
    @Override
    public Integer produceCloth() {
        System.out.println("Nike produces clothes.");
        return 100;
    }
}

public class dynamicProxy {
    public static void main(String[] args) {
        // 步骤 2: 创建目标对象
        NikeClothFactory nike = new NikeClothFactory();

        // 步骤 3: 获取类加载器
        ClassLoader classLoader = nike.getClass().getClassLoader();

        // 步骤 4: 获取接口数组
        Class<?>[] interfaces = nike.getClass().getInterfaces();

        // 步骤 5: 创建 InvocationHandler 实例
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 步骤 6: 实现 invoke 方法
                System.out.println("Proxy starts.");
                Object result = method.invoke(nike, args);
                System.out.println("Proxy ends.");
                return result;
            }
        };

        // 步骤 7: 创建代理对象
        ClothFactory proxy = (ClothFactory) Proxy.newProxyInstance(
                classLoader,
                interfaces,
                handler);

        // 步骤 8: 使用代理对象
        System.out.println(proxy.produceCloth());
    }
}
